<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\model\Rules;

class Rule extends BaseController
{
    public function index()
    {
        $this->checkLogin(true);
        $page = $this->request->param('page', 1);
        $data = Rules::page($page, 50)->select();
        return $this->success('success', $data);
    }

    public function read($id)
    {
        $this->checkLogin(true);
        $rule = Rules::find($id);
        if (empty($rule)) return $this->error('规则不存在');
        return $this->success('success', $rule);
    }

    public function save()
    {
        $this->checkLogin(true);
        $data = $this->request->post(['name', 'rule', 'status']);
        if ($data['rule'] == 'admin') return $this->error('超级权限不允许编辑');
        $rule = Rules::where('rule', $data['rule'])->find();
        if (!empty($rule)) return $this->error('规则标识已存在');
        $rule = Rules::create($data);
        return $this->success('success', $rule);
    }

    public function update($id)
    {
        $this->checkLogin(true);
        $data = $this->request->post(['name', 'rule', 'status']);
        if ($data['rule'] == 'admin') return $this->error('超级权限不允许编辑');
        $rule = Rules::find($id);
        if (empty($rule)) return $this->error('规则不存在');
        if ($rule->rule == 'admin') return $this->error('超级权限不允许编辑');
        $rule->save($data);
        return $this->success('success', $rule);
    }

    public function delete($id)
    {
        $this->checkLogin(true);
        if ($id == 1) return $this->error('超级权限不允许编辑');
        $rule = Rules::find($id);
        if ($rule->rule == 'admin') return $this->error('超级权限不允许编辑');
        $rule->delete();
        return $this->success('delete success');
    }
}
